package se.sweco.gpsservice;

import java.io.IOException;
import java.io.InputStream;

import se.sweco.gpsservice.datatypes.*;

import gnu.io.SerialPortEvent;
import gnu.io.SerialPortEventListener;

public class GPSListener implements SerialPortEventListener{
	InputStream input;
	StringBuffer inputBuffer;
	GPSConnect parent;
	GPSListener(InputStream input, GPSConnect parent) {
		this.input = input;
		inputBuffer = new StringBuffer();
		this.parent = parent;
	}
	
	public void serialEvent(SerialPortEvent arg0) {
		if(arg0.getEventType() == SerialPortEvent.DATA_AVAILABLE) {
			int newData = 0;
			try {
				newData = input.read();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			if( ((char) newData) != '\n' && ((char) newData) != '\r') {
				inputBuffer.append((char) newData);
			} else if (((char) newData) != '\r') {
				parseGPSData(inputBuffer.toString());
				inputBuffer = new StringBuffer();
			}
		}
	}

	private void parseGPSData(String data) {
		String[] gpsData = data.split(",");
		String gpsDataType = gpsData[0].substring(1);
		
		if(gpsDataType.equals("GPGGA")) { //Global Positioning System Fix Data
			GPSDataGPGGA gpgga = new GPSDataGPGGA();
			gpgga.parseData(data);
			parent.setGPGGA(gpgga);
			
			//System.out.println(gpgga);
		} else if(gpsDataType.equals("GPGLL")) { //Geographic Position
			GPSDataGPGLL gpgll = new GPSDataGPGLL();
			gpgll.parseData(data);
			parent.setGPGLL(gpgll);

			//System.out.println(gpgll);
		} else if(gpsDataType.equals("GPGSA")) { //GPS DOP
			GPSDataGPGSA gpgsa = new GPSDataGPGSA();
			gpgsa.parseData(data);
			parent.setGPGSA(gpgsa);

			//System.out.println(gpgsa);
		} else if(gpsDataType.equals("GPRMC")) {
			GPSDataGPRMC gprmc = new GPSDataGPRMC();
			gprmc.parseData(data);
			parent.setGPRMC(gprmc);

			//System.out.println(gprmc);
		} else if(gpsDataType.equals("GPVTG")) {
			GPSDataGPVTG gpvtg = new GPSDataGPVTG();
			gpvtg.parseData(data);
			parent.setGPVTG(gpvtg);

			//System.out.println(gpvtg);
		} else if(gpsDataType.equals("GPGSV")) {
			GPSDataGPGSV gpgsv = new GPSDataGPGSV();
			gpgsv.parseData(data);
			//System.out.println(gpgsv);
		} else {
			System.out.println("Unknown");
		}
	}
}
